﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using orm.efcore.api.Entities;

namespace orm.efcore.api.Controllers
{
    /// <summary>
    /// 多表操作（核心是导航属性）
    /// </summary>
    public class MultipleController(CoreDbContext dbContext) : EfCoreBaseController(dbContext)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now,
                OrderDetails =
                [
                    new()
                    {
                        ProductName = "导航新增",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    },
                    new()
                    {
                        ProductName = "导航新增2",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    }
                ]
            };

            DbContext.Add(order);
            await DbContext.SaveChangesAsync();
            
            return Ok("Id：" + order.Id);
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            var order = await DbContext.Order
                .Include(o => o.OrderDetails)
                .SingleOrDefaultAsync(o => o.Id == id);

            if (order != null)
            {
                DbContext.Remove(order);
                return Ok(await DbContext.SaveChangesAsync() > 0);
            }

            return Ok("Null");
        }

        [HttpGet]
        public async Task<IActionResult> PageList(int pageIndex, int pageSize)
        {
            int skip = (pageIndex - 1) * pageSize;
            var query = DbContext.Order
                .Include(o => o.OrderDetails)
                .Where(o => o.IsDeleted == false);

            var rows = await query
                .OrderByDescending(o => o.Id)
                .Skip(skip)
                .Take(pageSize)
                .ToListAsync();

            int total = await query.CountAsync();
            return Ok(new { rows, total });
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            return Ok(await DbContext.Order
                .Include(o => o.OrderDetails)
                .SingleOrDefaultAsync(o => o.Id == id));
        }
    }
}
